#    This is part of WeatherFront.
#
#    Copyright (C) 2010 Stefan Sieber
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; version 2 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#


import objc
import Foundation
import AppKit
import time

import PyFR.Utilities

import urllib2
import re
import string

from WeatherFrontXMLScanner import *
from WeatherFrontWeatherDotCom import * 
from WeatherFrontIpInfoDbDotCom import * 

from WeatherTranslate import tr



verbose=1
def log(s,level=1):
	if verbose >= level:
		Foundation.NSLog( u"WeatherFrontLog: WeatherController: %@",  s ) 
	pass
	


# Weather Item
class WeatherItem(PyFR.Utilities.ControllerUtilities):
	def __init__(self,item):
		self.id=item
		self.caption = "ERROR"
		self.unitTemp = " " #C/F
		self.unitSpeed = " " #kmh / mph
		self.temp1=" "	#high/current
		self.temp2=" "	#low/feels-like
		self.text="Something is wrong here. Probably is just a temporary issue with the network. If the problem persists, you might want to check the Console.app output and open a ticket at code.google.com/p/weatherfront"
		self.location=" "
		self.date=" " #lupdate/date
		self.icon="na"
		self.windFrom=" "
		self.windStrength=" "
		self.hmid=" "

	def GetName(self):
		if self.id == 0:
			retval = tr("Today")
		else:
			retval = tr(self.caption)
			
		return retval


	def GetPreviewImagePath(self):
		return ("/System/Library/CoreServices/Front Row.app/Contents/PlugIns/WeatherFront.frappliance/Contents/Resources/icons/%s.png" % self.icon)




class WeatherController(PyFR.Utilities.ControllerUtilities):
	def __init__(self):
		self = self
		self.internetConnection = 1
		self.rawXml = ''
		self.city = ' '
		self.country = ' '
		self.state = ' '
		self.zip = 0
		self.locationCode = ' '
		self.units = ''
		
	def DownloadWeather(self):
		#url = "http://xoap.weather.com/weather/local/GMXX5312?cc=*&dayf=5&link=xoap&prod=xoap&par=1173899084&key=75c64d1ebc6ef7f7"
		url = ("http://xoap.weather.com/weather/local/%s?cc=*&dayf=5&link=xoap&prod=xoap&par=1173899084&key=75c64d1ebc6ef7f7" % self.locationCode)
		
		
		if self.units == "M":
			url = url + '&unit=m'
		log(url)
		try:
			handler = urllib2.urlopen(url)
			self.rawXml = handler.read()
			handler.close()
			#log(self.rawXml)
			return 1
		except:
			log("WeatherAPI::DownloadWeather - no internet connection")
			self.internetConnection = 0
			return 0 #error
	

		
		
	def DownloadLocationIDs(self):
		log("DownloadLocationIDs for: %s" % self.city)
		#url = "http://xoap.weather.com/search/search?where=Berlin"
		url = ("http://xoap.weather.com/search/search?where=%s" % self.city)
		log(url)
		
		try:
			handler = urllib2.urlopen(url)
			self.rawXml = handler.read()
			handler.close()
			#log(self.rawXml)
			return 1
		except:
			log("WeatherAPI::DownloadLocationInformation - no internet connection")
			self.internetConnection = 0
			return 0 #error

		
		
	def DownloadLocation(self):
		log("DownloadLocation from ipinfodb.com")
		url = "http://api.ipinfodb.com/v2/ip_query.php?key=1b8fde1105c5b50f0f8416b50ec581c3bc7aa1b0e7f352a8762299d40ddf6c87"
		#log(url)
		
		try:
			handler = urllib2.urlopen(url)
			#self.rawXml = "<Response><Ip>199.239.136.200</Ip><Status>OK</Status><CountryCode>US</CountryCode><CountryName>United States</CountryName><RegionCode>08</RegionCode><RegionName>Colorado</RegionName><City>Englewood</City><ZipPostalCode>80112</ZipPostalCode><Latitude>39.569</Latitude><Longitude>-104.858</Longitude><Timezone>0</Timezone><Gmtoffset>0</Gmtoffset><Dstoffset>0</Dstoffset></Response>"
			self.rawXml = handler.read()
			handler.close()
			#log(self.rawXml)
			return 1
		except:
			log("WeatherAPI::DownloadLocation - no internet connection")
			self.internetConnection = 0
			return 0 #error
		
			
			
			
			
	def ReadConfigFile(self):
		log("LanguageCode: %s" % Foundation.NSUserDefaults.standardUserDefaults().objectForKey_('AppleLanguages')[0]) #This is just FYI, compare translation.py
		infile = file('/System/Library/CoreServices/Front Row.app/Contents/PlugIns/WeatherFront.frappliance/Contents/Resources/mySettings.txt', 'r')
		for line in infile.readlines():
			#log(line)
			if string.find(line, '#') != -1:
				pass
			elif string.find(line, 'LOCATIONCODE') != -1:
				value = string.split(line, '=')
				value[1] = string.rstrip(value[1], '\n')
				self.locationCode = value[1]
				log('ConfigFile: Location: %s' % self.locationCode)
			elif string.find(line, 'UNITS') != -1:
				value = string.split(line, '=')
				value[1] = string.rstrip(value[1], '\n')
				self.units = value[1]
				log('ConfigFile: Units: %s' % self.units)
		infile.close()
		
		if self.locationCode == 'AUTO':
			log("Try to retrieve location code ...")
			if self.DownloadLocation() == 1:
				log("Parse location XML from ipinfodb.com")
				xmlScanner = XMLscanner()
				xmlScanner.scan(self.rawXml)
				xmlCompiler = IpInfoDbDotComCompiler(xmlScanner)
				xmlCompiler.getCurrentLocation(self)
				
				if self.zip != 0: # US
					log("US City - use zip code")
					self.locationCode = self.zip
					if self.units == 'AUTO':
						log("Units set to AUTO - use (F)ahrenheit")
						self.units = 'F'
				
				else:
					log("No US city")
					
					if self.units == 'AUTO':
						log("Units set to AUTO - use (M)etric")
						self.units = 'M'
					
					log("Parse location XML from weather.com ...")
					if self.DownloadLocationIDs() == 1:
						xmlScanner = XMLscanner()
						xmlScanner.scan(self.rawXml)
						xmlCompiler = WeatherDotComCompiler(xmlScanner)
						self.locationCode = xmlCompiler.getLocationID(self.city, self.country)
					else:
						log("WeatherAPI::ReadConfigFile:return from DownloadLocationInformation - download failed")
			else:
				log("WeatherAPI::ReadConfigFile:return from DownloadLocation - download failed")
		else:
			log("LocationCode is set fix to %s" % self.locationCode)

		return
		

	def GetWeatherItems(self):
		log("WeatherAPI::GetWeatherItems")
		
		retval=[]
		
		
		if self.DownloadWeather() == 1:
			xmlScanner = XMLscanner()
			xmlScanner.scan(self.rawXml)
			
			
			if xmlScanner.xml_stream.__len__() > 10: # XML seems to be okay
			
				xmlCompiler = WeatherDotComCompiler(xmlScanner)
			
				# current condition
				cc = WeatherItem('cc')
				xmlCompiler.getCurrentConditions(cc)
				retval.append(cc)
			
				# forecast
				fc0 = WeatherItem(0)
				xmlCompiler.getForecast(fc0)
				if fc0.temp1 != "N/A":
					retval.append(fc0)
				else:
					log('Forecast for Today partly N/A - drop it')
			
				fc1 = WeatherItem(1)
				xmlCompiler.getForecast(fc1)
				retval.append(fc1)
			
				fc2 = WeatherItem(2)
				xmlCompiler.getForecast(fc2)
				retval.append(fc2)
			
				fc3 = WeatherItem(3)
				xmlCompiler.getForecast(fc3)
				retval.append(fc3)
			
			else: # XML to short
				log('XML length: %s' % xmlScanner.xml_stream.__len__())
				log(self.rawXml)
				error = WeatherItem("0")
				retval.append(error)
			

		else: # download did not work
			error = WeatherItem("0")
			retval.append(error)

		return retval



WeatherController=WeatherController()
WeatherController.ReadConfigFile()


